<?php
namespace app\admin\controller;

use app\common\model\Admin as AdminModel;

class Admin extends Common
{
    public function index()
    {
        $this->setMetaTitle('管理员管理');

        $model = new AdminModel;
        $lists = $this->lists($model, [], 'group ASC, id DESC', '*');

        $this->assign('lists', $lists);
        return $this->fetch();
    }

    public function add()
    {
        if($this->request->isPost()){
            $name = $this->request->post('name');
            $group = $this->request->post('group');
            $passwd = $this->request->post('passwd');

            $model = new AdminModel;

            if(!$group){
                $this->error('管理员类型没有选择');
            }
            if(!$name){
                $this->error('管理员账号没有填写');
            }

            $hasName = $model->where('name', $name)->count();
            if($hasName){
                $this->error('管理员账号已存在，请重设');
            }
            if(!$passwd){
                $this->error('管理员密码没有填写');
            }

            $data = [
                'group' => $group,
                'name' => $name,
                'passwd' => md5($passwd),
                'status' => 1
            ];
            $model->isUpdate(false)->save($data);

            $this->success('添加管理员账号成功', 'admin/index');

        }else {
            $this->setMetaTitle('添加管理员');
            $this->assign('adminGroups', AdminModel::ADMIN_GROUPS);
            return $this->fetch('edit');
        }
    }

    public function edit($id)
    {
        $info = AdminModel::get($id);
        if(!$info){
            $this->error('管理员数据不存在', 'admin/index');
        }

        if($this->request->isPost()){
            $passwd = $this->request->post('passwd');

            $model = new AdminModel;

            if(!$passwd){
                $this->error('管理员密码没有填写');
            }

            $data = [
                'id' => $id,
                'passwd' => md5($passwd),
            ];
            $model->isUpdate(true)->save($data);

            $this->success('编辑管理员账号成功', 'admin/index');

        }else {
            $this->setMetaTitle('编辑管理员');
            $this->assign('adminGroups', AdminModel::ADMIN_GROUPS);
            $this->assign('info', $info);
            return $this->fetch('edit');
        }
    }

    public function mypwd()
    {
        if($this->request->isPost()) {
            $oldpwd = input('oldpwd');
            $newpwd = input('newpwd');
            $newpwd2 = input('newpwd2');

            if (!$oldpwd) {
                $this->error('原始密码没有填写');
            }

            if (!$newpwd) {
                $this->error('新密码没有填写');
            }

            if ($newpwd != $newpwd2) {
                $this->error('重复密码填写不一致');
            }

            $this->adminInfo->data('passwd', md5($newpwd))->save();

            $this->success('密码修改成功');
        }else{
            $this->setMetaTitle('修改密码');
            return $this->fetch();
        }
    }

}


